
import urllib.request

# get
'''
res = urllib.request.urlopen("http://www.baidu.com")
print(res.read().decode('utf-8')) # 对获取到的网页源码进行 utf-8 解码
'''


'''
# 超时处理
try:
    res = urllib.request.urlopen("http://httpbin.org/get", timeout=0.01)
    print(res.read().decode('utf-8')) # 对获取到的网页源码进行 utf-8 解码
except Exception as e:
    print(e)
'''


'''
# post 测试 httpbin.org
import urllib.parse
formData = bytes(urllib.parse.urlencode({"name":"tlgen"}), encoding="utf-8")
res = urllib.request.urlopen("http://httpbin.org/post", formData)
print(res.read().decode("utf-8"))
'''

'''
res = urllib.request.urlopen("http://httpbin.org/get")
print(res.status)
print(res.getheaders())
print(res.getheader("server"))
'''

headers = {  # 伪装成是浏览器请求
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
}
url = "http://httpbin.org/post"
data = bytes(urllib.parse.urlencode({"name":"tlgen"}), encoding="utf-8")
req = urllib.request.Request(url=url,data=data,headers=headers,method="POST")
res = urllib.request.urlopen(req)
print(res.read().decode("utf-8"))